//
//  NGLocalMessageViewController.m
//  NetMobileLocation
//
//  Created by Mehmet Sinan Şahin on 2/9/12.
//  Copyright (c) 2012 netgis. All rights reserved.
//

#import "NGLocalMessageViewController.h"
#import "NGWeb.h"
#import "NGUtility.h"
#import "NSDate+Extensions.h"
#import "LoadingView.h"
#import "SoapFault.h"
#import <QuartzCore/QuartzCore.h>

@implementation NGLocalMessageViewController

@synthesize toMessagesButtonItem;
@synthesize sendButtonItem;
@synthesize navItem;
@synthesize messageBodyTextView;
@synthesize messageType;
@synthesize loadingView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil messageType: (LOCAL_MESSAGE_TYPE) pMessageType
{
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        nibNameOrNil = [nibNameOrNil stringByAppendingString:@"-ipad"];
    }
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIButton* backButton = [UIButton buttonWithType:101];
        [backButton setTitle:TTLocalizedString(@"Messages", @"") forState:UIControlStateNormal];
        [backButton addTarget:self 
                       action:@selector(toMessages:)
             forControlEvents:UIControlEventTouchUpInside];
        toMessagesButtonItem = [[UIBarButtonItem alloc] initWithCustomView: backButton];
        
        UIButton* sendButton = [UIButton buttonWithType:100];
        [sendButton setTitle:TTLocalizedString(@"Send", @"")forState:UIControlStateNormal];
        [sendButton addTarget:self 
                       action:@selector(sendMessage:)
             forControlEvents:UIControlEventTouchUpInside];
        sendButtonItem = [[UIBarButtonItem alloc] initWithCustomView: sendButton];
        [sendButtonItem setEnabled:FALSE];
        messageBodyTextView.layer.cornerRadius = 10.0f;
        messageType = pMessageType;
        
        [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg.png"]]];

    }
    return self;
}

-(IBAction)toMessages:(id)sender {
    [self.view removeFromSuperview];
}

-(IBAction)sendMessage:(id)sender {
    
    loadingView = [LoadingView loadingViewInView:[self.view.window.subviews objectAtIndex:0] loadingLabel:TTLocalizedString(@"Sending...", @"")];
	[loadingView
     performSelector:@selector(removeView)
     withObject:nil
     afterDelay:5.0];
    
    double lat = 99999999, lon = 99999999; 
    //TODO son konumu al
    NGLocation *location = [[[NGLocation alloc] init] autorelease];
    location.lat = lat;
    location.lon = lon;
    location.tarihSaat = [NSDate new];
    SendMessageRequest *request = [[SendMessageRequest alloc] initWithLocation:location];
    request.location = location;
    request.messageBody = messageBodyTextView.text;
    
    if (messageType == LOCAL_MESSAGE_TYPE_ALARM) {
        request.messageType = @"1";
        request.status = ALARM;
    }
    else if (messageType == LOCAL_MESSAGE_TYPE_TEXT) {
        request.messageType = @"0";
        request.status = UNKNOWN;
    }
    request.location.status = request.status;
    [WebServisCaller callWebService:request target:self];
}

#pragma mark - send message handler

- (void) sendMessageHandler: (id) value {
    SetLocationResponse *response = [SetLocationResponse alloc];
    NSString *dateStr = [[NSDate date] toFormattedString];
	if([value isKindOfClass:[NSError class]]) {
		NSLog(@"LOCAL MESSAGE -->NSERROR.....%@", value);
        response = [response initWithError:value];
	} else if([value isKindOfClass:[SoapFault class]]) {
		NSLog(@"LOCAL MESSAGE -->SOAP FAULT.....%@", value);
        response = [response initWithSoapFault:value];
	} else {
        NSLog(@"LOCAL MESSAGE -->setLocation returned the value:\n%@\n%@\n", dateStr, (NSString *) value);
        response = [response initWithResponseXml:(NSString*)value];
    }
    [loadingView removeView];
    NSString *message = nil, *title = nil;
    if (![response isSuccessful]) {
        title = TTLocalizedString(@"Error", @"");
        message = response.errorString;
    } else {
        title = TTLocalizedString(@"Successful...", @"");
        message = TTLocalizedString(@"Message sent", @"");
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                      message: message
                                                     delegate:nil
                                            cancelButtonTitle:TTLocalizedString(@"OK", @"")
                                            otherButtonTitles:nil];
    [alert show];
    [message release];
    [title release];
    [alert release]; 
}

#pragma mark - textview delegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    return TRUE;
}

- (void)textViewDidChange:(UITextView *)textView {
    [sendButtonItem setEnabled:![NSString isEmpty:textView.text]];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range 
 replacementText:(NSString *)text {
    // Any new character added is passed in as the "text" parameter
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return FALSE;
    }
    return TRUE;
}


#pragma mark - View lifecycle

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [navItem setLeftBarButtonItem:toMessagesButtonItem animated:false];
    [navItem setRightBarButtonItem:sendButtonItem animated:false];
    
    /*
    NSString *mesType = @"";
    if (messageType == LOCAL_MESSAGE_TYPE_TEXT) {
        mesType = TTLocalizedString(@"Text", @"");
    } else {
        mesType = TTLocalizedString(@"Alarm", @"");
    }
    mesType = @"";
    
    [navItem setTitle:[NSString stringWithFormat:TTLocalizedString(@"New Message[%@]", @""), mesType]];
    */
    
    if (messageType == LOCAL_MESSAGE_TYPE_TEXT) {
        [imgNavItemTitle setImage:[UIImage imageNamed: @"ic_text.png"]];
    } else if (messageType == LOCAL_MESSAGE_TYPE_ALARM) {
        [imgNavItemTitle setImage:[UIImage imageNamed: @"ic_alarm.png"]];
    } else {
        [imgNavItemTitle setImage:[UIImage imageNamed: @"delete.png"]];        
    }

    [lblNavItemTitle setText:TTLocalizedString(@"New Message", @"")];
    [navItemTitleView setBackgroundColor:[UIColor clearColor]];
    navItem.titleView = navItemTitleView;

    messageBodyTextView.layer.cornerRadius = 10.0f;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [toMessagesButtonItem release];
    [sendButtonItem release];
    [navItem release];
    [messageBodyTextView release];
}

@end
